<template>
  <BasicModal 
  :title="modalType ? '编辑' : '新增'"
  :width="360"
  v-bind="$attrs" 
  @register="register"
  @ok="onModalConfirm">
    <BasicForm 
    ref="formElRef"
    :schemas="formSchemas" 
    :showActionButtonGroup="false" />
  </BasicModal>
</template>

<script lang="ts" setup>
import _ from 'lodash-es'
import { ref, defineEmits } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, FormSchema, FormActionType  } from '@/components/Form'

const modalType = ref(false);

const formElRef = ref<Nullable<FormActionType>>(null);

const emits = defineEmits(['onConfirm']);

const [register] = useModalInner((data) => {
  const isEdit = _.get(data, 'isEdit', false);
  modalType.value = isEdit;
  if (isEdit) {
    formElRef.value?.setFieldsValue(data);
  } else {
    formElRef.value?.resetFields();
  }
})

const formSchemas: FormSchema[] = [
  {
    field: 'name',
    component: 'Input',
    label: '角色名字',
    required: true,
  },
  {
    field: 'code',
    component: 'Input',
    label: '角色编码',
    required: true,
  }
]

async function onModalConfirm() {
  await formElRef.value?.validate();
  const formData = formElRef.value?.getFieldsValue();
  emits('onConfirm', formData);
}

</script>